package com.module.systemConfig.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import base.dao.GenericHibernateDao;
import base.util.Page;
import com.module.systemConfig.vo.SystemConfig;

public class SystemConfigDao extends GenericHibernateDao<SystemConfig, Long> {
	private SystemConfigDao() {
	}

	private static SystemConfigDao dao;

	public synchronized static SystemConfigDao getInstance() {
		if (dao == null)
			dao = new SystemConfigDao();
		return dao;
	}

	/**
	 * 查询列表
	 * 
	 * @param session
	 * @param bean
	 * @param start
	 * @param limit
	 * @return
	 * @throws SQLException
	 */
	public Page getList(Session session, SystemConfig bean, Integer start,
			Integer limit) throws SQLException {
		Page page = new Page();
		StringBuffer sb = new StringBuffer();
		StringBuffer condition = new StringBuffer();
		List<Object> params = new ArrayList<Object>();

		if (bean.getConfigKey() != null && !"".equals(bean.getConfigKey())) {
			condition.append(" and obj.configKey like ?");
			params.add("%" + bean.getConfigKey() + "%");
		}
		// if(bean.getConfigType()!=null&&!"".equals(bean.getConfigType())){
		// condition.append(" and obj.configType like ?");
		// params.add("%"+bean.getConfigType() + "%");
		// }
		// if(bean.getDataType()!=null&&!"".equals(bean.getDataType())){
		// condition.append(" and obj.dataType like ?");
		// params.add("%"+bean.getDataType() + "%");
		// }

		sb.append("from SystemConfig as obj where 1=1 and status <> 'D'");
		sb.append(condition);
		// sb.append(" order by status asc,type desc,createTime desc ");

		Query query = session.createQuery(sb.toString());
		int i = 0;
		for (Object obj : params) {
			query.setParameter(i, obj);
			i++;
		}
		query.setFirstResult(start).setMaxResults(limit);

		Query totalQuery = session
				.createQuery("select count(*) from SystemConfig as obj where 1=1  and status <> 'D'"
						+ condition);
		int j = 0;
		for (Object obj : params) {
			totalQuery.setParameter(j, obj);
			j++;
		}
		page.setTotal((long) ((Long) totalQuery.uniqueResult()).intValue());

		page.setRows(query.list());
		return page;
	}
}
